<template>
  <div class="bank-card-container">
    <el-card>
      <div slot="header" class="header">
        <span>银行卡管理</span>
        <el-button type="primary" @click="handleAdd">新增银行卡</el-button>
      </div>

      <el-table
        :data="cardList"
        style="width: 100%"
        v-loading="loading">
        <el-table-column
          prop="bankName"
          label="银行名称"
          width="180">
        </el-table-column>
        <el-table-column
          prop="cardNumber"
          label="卡号"
          width="200">
          <template slot-scope="scope">
            {{ maskCardNumber(scope.row.cardNumber) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="cardType"
          label="卡类型"
          width="120">
        </el-table-column>
        <el-table-column
          prop="balance"
          label="余额"
          width="150">
          <template slot-scope="scope">
            ¥{{ scope.row.balance }}
          </template>
        </el-table-column>
        <el-table-column
          prop="remarks"
          label="备注">
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="150">
          <template slot-scope="scope">
            <el-button
              @click="handleEdit(scope.row)"
              type="text"
              size="small">
              编辑
            </el-button>
            <el-button
              @click="handleDelete(scope.row)"
              type="text"
              size="small"
              class="delete-btn">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="cardForm" :rules="rules" ref="cardForm" label-width="100px">
        <el-form-item label="银行名称" prop="bankName">
          <el-input v-model="cardForm.bankName"></el-input>
        </el-form-item>
        <el-form-item label="卡号" prop="cardNumber">
          <el-input v-model="cardForm.cardNumber"></el-input>
        </el-form-item>
        <el-form-item label="卡类型" prop="cardType">
          <el-select v-model="cardForm.cardType" placeholder="请选择卡类型">
            <el-option v-for="item in cardTypes" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="余额" prop="balance">
          <el-input-number v-model="cardForm.balance" :precision="2" :step="0.1" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" v-model="cardForm.remarks"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'BankCard',
  data() {
    return {
      cardList: [],
      loading: false,
      dialogVisible: false,
      dialogTitle: '新增银行卡',
      cardForm: {
        bankName: '',
        cardNumber: '',
        cardType: '',
        balance: 0,
        remarks: ''
      },
      rules: {
        bankName: [
          { required: true, message: '请输入银行名称', trigger: 'blur' }
        ],
        cardNumber: [
          { required: true, message: '请输入卡号', trigger: 'blur' }
        ],
        cardType: [
          { required: true, message: '请选择卡类型', trigger: 'change' }
        ]
      },
      cardTypes: [
        { value: '储蓄卡', label: '储蓄卡' },
        { value: '信用卡', label: '信用卡' }
      ]
    }
  },
  created() {
    this.fetchCardList()
  },
  methods: {
    async fetchCardList() {
      this.loading = true
      try {
        const response = await this.$http({
          url: '/card/list',
          method: 'get',
          params: {
            pageNo: 1,
            pageSize: 10
          }
        })
        if (response.data.code === 20000) {
          this.cardList = response.data.data.rows || []
        } else {
          throw new Error(response.data.message || '获取银行卡列表失败')
        }
      } catch (error) {
        console.error('Fetch card list error:', error)
        this.$message.error('获取银行卡列表失败')
      } finally {
        this.loading = false
      }
    },
    maskCardNumber(cardNumber) {
      if (!cardNumber) return ''
      return cardNumber.replace(/^(\d{4})\d+(\d{4})$/, '$1 **** **** $2')
    },
    handleAdd() {
      this.dialogTitle = '新增银行卡'
      this.cardForm = {
        bankName: '',
        cardNumber: '',
        cardType: '',
        balance: 0,
        remarks: ''
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑银行卡'
      this.cardForm = { ...row }
      this.dialogVisible = true
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该银行卡吗？', '提示', {
          type: 'warning'
        })
        const response = await this.$http({
          url: `/card/${row.id}`,
          method: 'delete'
        })
        if (response.data.code === 20000) {
          this.$message.success('删除成功')
          this.fetchCardList()
        } else {
          throw new Error(response.data.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('Delete card error:', error)
          this.$message.error('删除失败')
        }
      }
    },
    submitForm() {
      this.$refs.cardForm.validate(async valid => {
        if (valid) {
          try {
            let response
            if (this.cardForm.id) {
              response = await this.$http({
                url: '/card',
                method: 'put',
                data: this.cardForm
              })
            } else {
              response = await this.$http({
                url: '/card',
                method: 'post',
                data: this.cardForm
              })
            }
            
            if (response.data.code === 20000) {
              this.$message.success(this.cardForm.id ? '更新成功' : '添加成功')
              this.dialogVisible = false
              this.fetchCardList()
            } else {
              throw new Error(response.data.message || '操作失败')
            }
          } catch (error) {
            console.error('Submit form error:', error)
            this.$message.error('操作失败')
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.bank-card-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.delete-btn {
  color: #F56C6C;
}
</style> 